package org.lyl.taobao.dao.impl;

import org.lyl.taobao.api.entity.Order;
import org.lyl.taobao.api.utils.DruidConnectionUtils;
import org.lyl.taobao.dao.IOrderDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Re
 * @Date: 2021/4/9 20:46
 */
public class OrderDaoImpl implements IOrderDao {
    DruidConnectionUtils druidConnectionUtils=new DruidConnectionUtils();
    @Override
    public boolean addOrder(Connection connection, Order order) {
        PreparedStatement preparedStatement = null;
        String sql = "insert into `order`(userId,c_Id,merchantId) values (?,?,?);";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,order.getOrderUserId());
            preparedStatement.setInt(2,order.getOrderCommodityId());
            preparedStatement.setInt(3,order.getOrderMerchantId());
            if (preparedStatement.executeUpdate() == 1) {
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,null);
        }
        return false;
    }

    @Override
    public List<Order> checkOrder(Connection connection, Integer userId) {
        List<Order> orderList = new ArrayList<>();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String sql ="select * from `order` where userId = ?;";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,userId);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                orderList.add(new Order(resultSet.getInt("orderId"),resultSet.getInt("userId"),resultSet.getInt("c_Id"),resultSet.getInt("merchantId")));
            }
            return orderList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,resultSet);
        }
        return null;
    }

    @Override
    public boolean deleteOrder(Connection connection, Integer orderId) {
        PreparedStatement preparedStatement = null;
        String sql = "delete from `order` where orderId = ?;";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,orderId);
            if (preparedStatement.executeUpdate() == 1) {
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,null);
        }
        return false;
    }
}
